package httputil.httpclientauth;

import httputil.okhttpinterceptor.HTTPKerberosAuthInterceptor;
import okhttp3.*;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthSchemeProvider;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.config.Lookup;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.impl.auth.SPNegoSchemeFactory;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.security.auth.Subject;
import javax.security.auth.kerberos.KerberosPrincipal;
import javax.security.auth.login.AppConfigurationEntry;
import javax.security.auth.login.Configuration;
import javax.security.auth.login.LoginContext;
import java.io.IOException;
import java.security.Principal;
import java.security.PrivilegedAction;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

public class RequestKerberosUrlUtils2 {
    public static Logger logger = LoggerFactory.getLogger(RequestKerberosUrlUtils2.class);
    private String principal;
    private String keyTabLocation;
    static final private ConnectionPool connectionPool = new ConnectionPool();
    public RequestKerberosUrlUtils2() {
    }

    public RequestKerberosUrlUtils2(String principal, String keyTabLocation) {
        super();
        this.principal = principal;
        this.keyTabLocation = keyTabLocation;
    }

    public RequestKerberosUrlUtils2(String principal, String keyTabLocation, boolean isDebug) {
        this(principal, keyTabLocation);
        if (true) {
            System.setProperty("sun.security.spnego.debug", "true");
            System.setProperty("sun.security.krb5.debug", "true");
        }
    }

    public RequestKerberosUrlUtils2(String principal,
                                    String keyTabLocation,
                                    String krb5ConfLocation,
                                    boolean isDebug) {
        this(principal, keyTabLocation, isDebug);
        System.setProperty("java.security.krb5.conf", krb5ConfLocation);
    }

    //模拟curl使用kerberos认证
    private static OkHttpClient buildSpengoHttpClient() {
        OkHttpClient.Builder clientBldr = new OkHttpClient.Builder()
                 .followRedirects(false)
                 .followSslRedirects(false)
                // all clients share a single connection pool
                .connectionPool(connectionPool)
                // cookies are ignored (except when a Transaction is being used)
                //.cookieJar(CookieJar.NO_COOKIES)
                // no timeouts since some of our clients' reads and writes can be massive
                .readTimeout(0, TimeUnit.SECONDS)
                .writeTimeout(0, TimeUnit.SECONDS);
        String host = "c286ghr.ecom.bigdata.int.thomsonreuters.com";
        Interceptor interceptor = new HTTPKerberosAuthInterceptor(host );


        if(interceptor != null)
            clientBldr.addInterceptor(interceptor);

        OkHttpClient  client = clientBldr.build();
        return client;
    }

    public  Response callRestRequest(Request request, final String keberosUser) {
        logger.info(String.format("Calling KerberosHttpClient %s %s ", this.principal, this.keyTabLocation));

        Configuration config = new Configuration() {
            @SuppressWarnings("serial")
            @Override
            public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
                return new AppConfigurationEntry[]{new AppConfigurationEntry("com.sun.security.auth.module.Krb5LoginModule",
                        AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, new HashMap<String, Object>() {
                    {
                        put("useTicketCache", "false");
                        put("useKeyTab", "true");
                        put("keyTab", keyTabLocation);
                        //Krb5 in GSS API needs to be refreshed so it does not throw the error
                        //Specified version of key is not available
                        put("refreshKrb5Config", "true");
                        put("principal", principal);
                        put("storeKey", "true");
                        put("doNotPrompt", "true");
                        put("isInitiator", "true");
                        put("debug", "true");
                    }
                })};
            }
        };
        Set<Principal> princ = new HashSet<Principal>(1);
        princ.add(new KerberosPrincipal(keberosUser));
        Subject sub = new Subject(false, princ, new HashSet<Object>(), new HashSet<Object>());
        try {
            //认证模块：Krb5Login
            LoginContext lc = new LoginContext("Krb5Login", sub, null, config);
            lc.login();
            Subject serviceSubject = lc.getSubject();
            return Subject.doAs(serviceSubject, new PrivilegedAction<Response>() {
                Response response = null;

                @Override
                public Response run() {
                    try {
                        //HttpUriRequest request = new HttpGet(url);

                        OkHttpClient spnegoHttpClient = buildSpengoHttpClient();
                        response = spnegoHttpClient.newCall(request).execute();

                        return response;
                    } catch (IOException ioe) {
                        ioe.printStackTrace();
                    }
                    return response;
                }
            });
        } catch (Exception le) {
            le.printStackTrace();
        }
        return null;
    }
}
